package com.yitiao.simple.buf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class NettyByteBufTest {
    public static void main(String[] args) {

        // 创建一个字节数组，容量 10
        ByteBuf buffer = Unpooled.buffer(10);

        for (int i = 0; i < 5; i++) {
            buffer.writeByte(i);
        }
        // this.writerIndex - this.readerIndex
        System.out.println(buffer.readableBytes());

        // buffer.writableBytes() this.capacity - this.writerIndex
        for (int i = 0; i < buffer.capacity(); i++) {
            System.out.println(buffer.readByte());
        }
        /**
         * Exception in thread "main" java.lang.IndexOutOfBoundsException:
         * readerIndex(5) + length(1) exceeds writerIndex(5):
         * UnpooledByteBufAllocator$InstrumentedUnpooledUnsafeHeapByteBuf(ridx: 5, widx: 5, cap: 10)
         * 	at io.netty.buffer.AbstractByteBuf.checkReadableBytes0(AbstractByteBuf.java:1442)
         * 	at io.netty.buffer.AbstractByteBuf.readByte(AbstractByteBuf.java:730)
         * 	at com.yitiao.simple.buf.NettyByteBufTest.main(NettyByteBufTest.java:19)
         */

        //使用for取出各个字节
        for(int i = 0; i < 10; i++) {
            System.out.println((char) buffer.getByte(i));
        }

        //按照某个范围读取
        System.out.println(buffer.getCharSequence(0, 4, StandardCharsets.UTF_8));
        System.out.println(buffer.getCharSequence(4, 6, StandardCharsets.UTF_8));

    }
}
